<template>
  <div class="component">
    <template v-if="Array.isArray(content)">
      <!-- content 是数组的处理 -->
      <div v-if="content[0]?.name" class="video_container">
        <img :src="thumbnail" />
        </div>
    </template>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType, watch, ref, onMounted } from 'vue';
export default defineComponent({
  name: 'Video',
  props: {
    id: {
      type: String as PropType<string>,
      default: "0000"
    },
    valueFromParent: {
      type: Object as PropType<Object>,
      required: true,
      default: {}
    },
  },
  setup(props) {
    const content = ref(props.valueFromParent?.moduleValue?.value);
    const thumbnail = ref('');

    const getVideoThumbnail = (videoUrl: string) => {
      return new Promise<string>((resolve, reject) => {
        const video = document.createElement('video');
        video.src = videoUrl;
        video.crossOrigin = 'anonymous';

        video.addEventListener('loadeddata', () => {
          video.currentTime = 1; // 设置视频的当前时间为1秒，以便截取该帧
        });

        video.addEventListener('seeked', () => {
          const canvas = document.createElement('canvas');
          canvas.width = video.videoWidth;
          canvas.height = video.videoHeight;
          const context = canvas.getContext('2d');
          if (context) {
            context.drawImage(video, 0, 0, canvas.width, canvas.height);
            resolve(canvas.toDataURL('image/png'));
          } else {
            reject('无法获取2D上下文');
          }
        });

        video.addEventListener('error', (e) => {
          reject('视频加载失败');
        });
      });
    };

    watch(() => props.valueFromParent, (newVal) => {
      content.value = newVal.moduleValue?.value;
      if (content.value && content.value[0]?.url) {
        getVideoThumbnail(content.value[0]?.url).then((thumbnailUrl) => {
          thumbnail.value = thumbnailUrl;
        }).catch((error) => {
          console.error(error);
        });
      }
    }, { deep: true });

    onMounted(() => {
      if (content.value && content.value[0]?.url) {
        getVideoThumbnail(content.value[0]?.url).then((thumbnailUrl) => {
          thumbnail.value = thumbnailUrl;
        }).catch((error) => {
          console.error(error);
        });
      }
    });

    return {
      content,
      thumbnail,
    };
  }
});
</script>

<style scoped>

.component {
  /* 样式 */
  color: white;
  border: 1px solid #ff8d1a;
  width: 345px;
  min-height: 40px;
  margin-top: 20px;
  background-color: #232323;
  border-radius: 10px;
  overflow: hidden; /* 确保 img 不会超出容器范围 */
}

.component img {
  width: 100%;
  height: auto; /* 保持图片比例 */
  display: block; /* 移除 img 默认的底部空白 */
}

</style>
